package com.kcsoft.controller;

import com.kcsoft.pojo.Result;
import com.kcsoft.pojo.User;
import com.kcsoft.service.UserService;
import com.kcsoft.utils.JwtUtil;
import com.kcsoft.utils.Md5Util;
import com.kcsoft.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @PostMapping("/register")
    public Result register(String username, String password){
        User user = userService.findByUsername(username);
        if (user == null) {
            String pwd = Md5Util.genPwd(password);
            userService.add(username, pwd);
            return Result.success();
        }
        return Result.error("用户名已存在");
    }

    @PostMapping("/login")
    public Result<String> login(String username, String password){
        String pwd = Md5Util.genPwd(password);
        User user = userService.findByUsername(username);
        if (user != null){
            if (user.getPassword().equals(pwd)){
                Map<String, Object> claims = new HashMap<>();
                claims.put("id", user.getId());
                claims.put("role", user.getRole());
                claims.put("username", username);
                return Result.success(JwtUtil.getAuthToken(claims));
            }
            return Result.error("密码错误");
        }
        return Result.error("用户名不存在");
    }

    @GetMapping ("/info")
    public Result<User> info(){
        Map<String, Object> claims = ThreadLocalUtil.get();
        String username = (String) claims.get("username");

        return Result.success(userService.findByUsername(username));
    }

    @PostMapping("/update")
    public Result<String> updates(@RequestParam String username,
                          @RequestParam(required = false) String stuId,
                          @RequestParam(required = false) String password,
                          @RequestParam(required = false) String name){
        userService.update(username, stuId, password, name);
        User user = userService.findByUsername(username);
        Map<String, Object> claims = new HashMap<>();
        claims.put("id", user.getId());
        claims.put("role", user.getRole());
        claims.put("username", username);
        ThreadLocalUtil.set(claims);
        String jwt = JwtUtil.getAuthToken(claims);
        return Result.success(jwt);
    }

}
